import smtplib
from email.mime.text import MIMEText

from order_platform.settings import EMAIL_SENDER, EMAIL_SENDER_CODE


def send_mail(to_email, email_code):
    print(f'sending {email_code} to {to_email}')

    # 配置邮箱信息
    sender = EMAIL_SENDER  # 发件人的地址
    password = EMAIL_SENDER_CODE  # 此处是我们刚刚在邮箱中获取的授权码
    receivers = [to_email, ]  # 邮件接受方邮箱地址，可以配置多个，实现群发
    # 邮件内容设置
    message = MIMEText(f'【订单管理平台】登录验证码 {email_code} ，10分钟内有效。', 'plain', 'utf-8')
    # 邮件标题设置
    message['Subject'] = '【订单管理平台】'
    # 发件人信息
    message['From'] = sender
    # 收件人信息
    message['To'] = receivers[0]
    # 通过授权码,登录邮箱,并发送邮件
    try:
        server = smtplib.SMTP('smtp.126.com')  # 配置126邮箱的smtp服务器地址
        server.login(sender, password)
        server.sendmail(sender, receivers, message.as_string())
        print('发送成功')
        server.quit()
        return True
    except smtplib.SMTPException as e:
        print('error', e)
        return False
